package pers.hl.module_main.common;
import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class DrawableUtil {

    /**
     * TextView四周drawable的序号。
     * 0 left,  1 top, 2 right, 3 bottom
     */
    private final int LEFT = 0;
    private final int TOP = 1;
    private final int RIGHT = 2;
    private final int BOTTOM = 3;

    private OnDrawableListener listener;
    private TextView mTextView;

    public DrawableUtil(TextView view) {
        mTextView = view;
    }

    public interface OnDrawableListener {
        default void onLeft(View v, Drawable left) {

        }

        default void onTop(View v, Drawable top) {

        }

        default void onRight(View v, Drawable right) {

        }

        default void onBottom(View v, Drawable bottom) {

        }
    }

    @SuppressLint("ClickableViewAccessibility")
    public void setListener(OnDrawableListener listener) {
        this.listener = listener;
        mTextView.setOnTouchListener(mOnTouchListener);
    }

    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    if (listener != null) {
                        Drawable drawableLeft = mTextView.getCompoundDrawables()[LEFT];
                        if (drawableLeft != null && event.getRawX() <= (mTextView.getLeft() + drawableLeft.getBounds().width())) {
                            listener.onLeft(v, drawableLeft);
                            return true;
                        }

                        Drawable drawableTop = mTextView.getCompoundDrawables()[TOP];
                        if (drawableTop != null && event.getRawY() >= (mTextView.getTop() + drawableTop.getBounds().height())) {
                            listener.onTop(v, drawableTop);
                            return true;
                        }

                        Drawable drawableRight = mTextView.getCompoundDrawables()[RIGHT];
                        if (drawableRight != null && event.getRawX() >= (mTextView.getRight() - drawableRight.getBounds().width())) {
                            listener.onRight(v, drawableRight);
                            return true;
                        }


                        Drawable drawableBottom = mTextView.getCompoundDrawables()[BOTTOM];
                        if (drawableBottom != null && event.getRawY() <= (mTextView.getBottom() - drawableBottom.getBounds().height())) {
                            listener.onBottom(v, drawableBottom);
                            return true;
                        }
                    }

                    break;
            }

            return false;
        }

    };
}
